package com.controller;

import com.dao.UserDao;
import com.model.Student;
import com.model.Teacher;
import com.model.Course;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;

@WebServlet("/admin/*")
public class AdminServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    private Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        
        try {
            if (pathInfo == null || "/".equals(pathInfo)) {
                resp.sendRedirect(req.getContextPath() + "/admin/students");
                return;
            }
            
            switch (pathInfo) {
                case "/students":
                    List<Student> students = userDao.getAllStudents();
                    req.setAttribute("students", students);
                    req.getRequestDispatcher("/WEB-INF/views/admin/students.jsp").forward(req, resp);
                    break;
                    
                case "/teachers":
                    List<Teacher> teachers = userDao.getAllTeachers();
                    req.setAttribute("teachers", teachers);
                    req.getRequestDispatcher("/WEB-INF/views/admin/teachers.jsp").forward(req, resp);
                    break;
                    
                case "/student/add":
                    req.getRequestDispatcher("/WEB-INF/views/admin/student-form.jsp").forward(req, resp);
                    break;
                    
                case "/student/edit":
                    int sno = Integer.parseInt(req.getParameter("sno"));
                    Student student = userDao.getStudentById(sno);
                    req.setAttribute("student", student);
                    req.getRequestDispatcher("/WEB-INF/views/admin/student-form.jsp").forward(req, resp);
                    break;
                    
                case "/teacher/add":
                    req.getRequestDispatcher("/WEB-INF/views/admin/teacher-form.jsp").forward(req, resp);
                    break;
                    
                case "/teacher/edit":
                    int tno = Integer.parseInt(req.getParameter("tno"));
                    Teacher teacher = userDao.getTeacherById(tno);
                    req.setAttribute("teacher", teacher);
                    req.getRequestDispatcher("/WEB-INF/views/admin/teacher-form.jsp").forward(req, resp);
                    break;
                    
                case "/courses":
                    List<Course> courses = userDao.getAllCourses();
                    req.setAttribute("courses", courses);
                    req.getRequestDispatcher("/WEB-INF/views/admin/courses.jsp").forward(req, resp);
                    break;
                    
                case "/course/add":
                    List<Teacher> teacherss = userDao.getAllTeachers();
                    req.setAttribute("teachers", teacherss);
                    req.getRequestDispatcher("/WEB-INF/views/admin/course-form.jsp").forward(req, resp);
                    break;
                    
                case "/course/edit":
                    String cno = req.getParameter("cno");
                    Course course = userDao.getCourseById(cno);
                    teachers = userDao.getAllTeachers();
                    req.setAttribute("course", course);
                    req.setAttribute("teachers", teachers);
                    req.getRequestDispatcher("/WEB-INF/views/admin/course-form.jsp").forward(req, resp);
                    break;
                    
                default:
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String pathInfo = req.getPathInfo();
        
        try {
            switch (pathInfo) {
                case "/student/save":
                    saveStudent(req, resp);
                    break;
                case "/teacher/save":
                    saveTeacher(req, resp);
                    break;
                case "/student/delete":
                    deleteStudent(req, resp);
                    break;
                case "/teacher/delete":
                    deleteTeacher(req, resp);
                    break;
                case "/course/save":
                    saveCourse(req, resp);
                    break;
                case "/course/delete":
                    deleteCourse(req, resp);
                    break;
                default:
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            sendError(resp, "数据库错误：" + e.getMessage());
        }
    }
    
    private void saveStudent(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        Student student = new Student();
        student.setSno(Integer.parseInt(req.getParameter("sno")));
        student.setSname(req.getParameter("sname"));
        student.setSsex(Integer.parseInt(req.getParameter("ssex")));
        student.setSage(Integer.parseInt(req.getParameter("sage")));
        student.setSdept(req.getParameter("sdept"));
        
        // 设置默认密码为学号
        String password = req.getParameter("sno");
        
        boolean isUpdate = userDao.getStudentById(student.getSno()) != null;
        if (isUpdate) {
            userDao.updateStudent(student);
        } else {
            userDao.addStudent(student, password);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "保存成功");
        resp.getWriter().write(gson.toJson(result));
    }
    
    private void saveTeacher(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        Teacher teacher = new Teacher();
        teacher.setTno(Integer.parseInt(req.getParameter("tno")));
        teacher.setTname(req.getParameter("tname"));
        teacher.setTsex(Integer.parseInt(req.getParameter("tsex")));
        teacher.setTmobile(req.getParameter("tmobile"));
        
        // 设置默认密码为教师号
        String password = req.getParameter("tno");
        
        boolean isUpdate = userDao.getTeacherById(teacher.getTno()) != null;
        if (isUpdate) {
            userDao.updateTeacher(teacher);
        } else {
            userDao.addTeacher(teacher, password);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "保存成功");
        resp.getWriter().write(gson.toJson(result));
    }
    
    private void deleteStudent(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        try {
            int sno = Integer.parseInt(req.getParameter("sno"));
            
            // 先检查是否有相关的作业提交记录
            if (userDao.hasStudentAssignments(sno)) {
                sendError(resp, "该学生有作业提交记录，不能删除");
                return;
            }
            
            userDao.deleteStudent(sno);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "删除成功");
            resp.getWriter().write(gson.toJson(result));
        } catch (NumberFormatException e) {
            sendError(resp, "无效的学号");
        }
    }
    
    private void deleteTeacher(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        try {
            int tno = Integer.parseInt(req.getParameter("tno"));
            
            // 先检查是否有相关的作业
            if (userDao.hasTeacherAssignments(tno)) {
                sendError(resp, "该教师有发布的作业，不能删除");
                return;
            }
            
            userDao.deleteTeacher(tno);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "删除成功");
            resp.getWriter().write(gson.toJson(result));
        } catch (NumberFormatException e) {
            sendError(resp, "无效的教师号");
        }
    }
    
    private void saveCourse(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        Course course = new Course();
        course.setCno(req.getParameter("cno"));
        course.setCname(req.getParameter("cname"));
        course.setCredit(Integer.parseInt(req.getParameter("credit")));
        course.setTno(Integer.parseInt(req.getParameter("tno")));
        
        boolean isUpdate = userDao.getCourseById(course.getCno()) != null;
        if (isUpdate) {
            userDao.updateCourse(course);
        } else {
            userDao.addCourse(course);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "保存成功");
        resp.getWriter().write(gson.toJson(result));
    }
    
    private void deleteCourse(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        try {
            String cno = req.getParameter("cno");
            
            if (userDao.hasCourseAssignments(cno)) {
                sendError(resp, "该课程有相关作业，不能删除");
                return;
            }
            
            userDao.deleteCourse(cno);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "删除成功");
            resp.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            sendError(resp, "删除失败：" + e.getMessage());
        }
    }
    
    private void sendError(HttpServletResponse resp, String message) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", message);
        resp.getWriter().write(gson.toJson(result));
    }
} 